package com.cskaoyan.service.impl;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.cskaoyan.bean.*;
import com.cskaoyan.mapper.StorageMapper;
import com.cskaoyan.service.StorageService;
import com.cskaoyan.utils.CommonUtil;
import com.cskaoyan.utils.RandomUtil;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.List;

/**
 * Description
 *
 * @author Qiu
 * @date Created on 2021/10/18
 */
@Service
public class StorageServiceImpl implements StorageService {

    @Autowired
    StorageMapper storageMapper;
    private String originalFilename;

    /**
     * @param file
     * @return
     */
    @Override
    public Storage create(HttpServletRequest req, MultipartFile file) {
       //获取文件名
        String originalFilename = file.getOriginalFilename();
        String key = RandomUtil.GetRandomString(15);
        //分离后缀
        int index = originalFilename.lastIndexOf(".");
        key += originalFilename.substring(index);
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //oss存储通行id和密码
        String accessKeyId = "LTAI5tJc5HsZyCKXiLiBhpfy";
        String accessKeySecret = "ZeuZfz7ohkZZqdlyBfHe3z9LbcIi59";

        //文件结点
        String endPoint = "oss-cn-shenzhen.aliyuncs.com";
        //文件夹
        String bucket = "cskaoyan8494";

        //创建链接
        OSSClient ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);
        //设置图片保存目录
        String fileName = "wx/storage/fetch/" + key;
        //设置响应头,图片格式,这样可以直接预览而不是下载
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType("image/"+ originalFilename.substring(index+1));
        //上传图片
        ossClient.putObject(bucket, fileName, inputStream,objectMetadata);

        String target = bucket + "." + endPoint;

        // 成功保存文件到本地后，保存文件信息到DB
        String url = "http://" + target + "/wx/storage/fetch/" + key;
        Storage storage = new Storage();
        storage.setKey(key);
        storage.setName(originalFilename);
        storage.setType(file.getContentType());
        storage.setSize((int) file.getSize());
        storage.setUrl(url);
        storage.setDeleted(0);
        storage.setAddTime(new Date());
        storage.setUpdateTime(new Date());

        StorageExample example = new StorageExample();
        storageMapper.insertSelective(storage);

        // 设置回显url，url映射静态资源路径在config中配置
        // storage.setUrl(url);

        return storage;
    }

    /**
     * 存储对象分页
     * @param key
     * @param name
     * @param param
     * @return
     */
    @Override
    public BasePageData<Storage> list(String key, String name, BaseParam param) {

        // 配置分页信息
        PageHelper.startPage(param.getPage(), param.getLimit());
        // 构造条件的对象
        StorageExample example = new StorageExample();
        StorageExample.Criteria criteria = example.createCriteria();
        if (CommonUtil.isStrNotEmpty(key)) {
            criteria.andKeyEqualTo(key);
        }
        if (CommonUtil.isStrNotEmpty(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        // 设置排序
        example.setOrderByClause(param.getSort() + " " + param.getOrder());
        List<Storage> storages = storageMapper.selectByExample(example);

        return BasePageData.ok(storages);
    }

    /**
     * 删除存储对象
     * @param storage
     */
    @Override
    public void delete(Storage storage) {
        storageMapper.deleteByPrimaryKey(storage.getId());
    }

    /**
     * 修改存储对象
     * @param storage
     */
    @Override
    public Storage update(Storage storage) {
        // 需要更新修改时间
        storage.setUpdateTime(new Date());

        storageMapper.updateByPrimaryKeySelective(storage);
        return storage;
    }
}
